<template>
  <div class="home_game_entry">
    <!-- banner -->
    <game-banner ref="gameBanner" :is-show-entry-btn="false" />

    <!-- 报名页面 -->
    <div v-loading="pageLoading" class="game_page">
      <div>
        <div>
          <div class="step_title">赛事报名</div>
          <el-steps class="step_mb" :active="stepActive">
            <!-- 步骤条, 不能使步骤条可以点击切换，会影响权限判定 -->
            <el-step v-for="(item, index) in stepList" :key="index" :title="item.title" :description="item.description" />
          </el-steps>
        </div>
        <div v-loading="!(UserType && gameInfo)" style="min-height:200px;position:relative;">
          <template v-if="UserType && gameInfo">
            <component
              :is="item.component"
              v-for="(item, index) in stepList"
              v-show="stepActive === index"
              :key="index"
              :ref="'entry-' + item.component"
              :is-show="stepActive === index"
              :user-type="UserType"
              :current-user-type="currentUserType"
              :dict="dict"
              :district="cache.district"
              :game-info="gameInfo"
              :user-info="userInfo"
              :user-team-info="userTeamInfo"
              :official-data="officialData"
              :required-id-data="requiredIdData"
              :attach-official="attachOfficial"
              @onPrevStep="doPrevStep"
              @onNextStep="doNextStep"
              @onChangeCurrentUserType="changeCurrentUserType"
              @onGetUserInfo="getUserInfo"
              @onGetUserTeamInfo="getUserTeamInfo"
              @onChangeOfficialData="changeOfficialData"
              @onAddAttachOfficial="addAttachOfficial"
              @reGetUserType="reGetUserType"
            />
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

import {
  api_POST_EventsManagementEntryOrderAllowEntry,
  api_GET_EventsManagementUserUserType, // 获取当前用户注册类型
  api_GET_EventsManagementCompetitionWithRoute,
  api_GET_EventsManagementRegisterId, // 获取注册信息
  api_GET_EventsManagementDelegationId // 获取团体注册信息
} from '@/extend/api/gameswaggerApi/app';

import StepByType from './components/stepByType';
import StepByInfo from './components/stepByInfo';
import StepByOfficial from './components/stepByOfficial';
import StepByAthlete from './components/stepByAthlete';
import StepBySubmit from './components/stepBySubmit';
import GameBanner from '../game/components/GameBanner/index';

export default {
  components: {
    StepByType,
    StepByInfo,
    StepByOfficial,
    StepByAthlete,
    StepBySubmit,
    GameBanner
  },
  data () {
    return {
      pageLoading: false, // 关键性Loading,，不可轻易false
      stepActive: 0, // 当前步骤位置
      stepList: [ // 步骤条数据
        {
          title: '确认信息',
          description: '请确认并完善相应信息',
          component: 'step-by-info'
        },
        {
          title: '选择教练',
          description: '请选择教练以及领队',
          component: 'step-by-official'
        },
        {
          title: '选手报名',
          description: '请选择要报名的运动员',
          component: 'step-by-athlete'
        },
        {
          title: '完成',
          description: '赛事报名成功',
          component: 'step-by-submit'
        }
      ],
      dynamicStepList: { // 动态步骤列表数据，此数据中的内容视情况添加进stepList
        stepByType: {
          title: '报名身份类型',
          description: '请确认报名身份类型',
          component: 'step-by-type'
        }
      },
      currentUserType: '', // 当前用户的选择的报名类型 Personal : 个人，Delegation：团体
      officialData: [], // 官员数据
      userInfo: null, // 用户信息
      userTeamInfo: null, // 团体信息
      gameInfo: null, // 赛事信息
      gameRoute: '', // 赛事路由
      gameTenantId: '', // 赛事tenantId
      gameId: '', // 赛事ID
      requiredIdData: { // 后续步骤需要的ID，此页面不要调用
        delegationId: '',
        registerId: ''
      },
      attachOfficial: [] // 存放附加的裁判教练或领队等
    };
  },
  computed: {
    ...mapState({
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    stepMaxLen () { // 步骤条最大值
      return this.stepList.length - 1;
    }
  },
  watch: {
    'UserType': {
      immediate: true,
      deep: true,
      handler(val) {
        // 获取当前用户角色 Personal : 个人，Delegation：团体， PersonalDelegation：个人 + 团体
        if (val) {
          this.requiredIdData.registerId = val.registerId;
          this.requiredIdData.delegationId = val.delegationId;
          this.getUserInfo();
          this.getUserTeamInfo();
          if (this.stepList.length === 4 && val.userType.code === 'PersonalDelegation') {
            this.stepList.unshift(this.dynamicStepList.stepByType);
          }
          this.checkUserAndUserteamReady();
        }
      }
    },
    currentUserType() {
      // currentUserType 变更后需 changeRequiredIdData
      this.changeRequiredIdData();
    }
  },
  created() {
    const $route = this.$route;
    const _paramsId = $route.params.id;
    // this.stepActive = $route.query.insurance?4:0;
    this.gameRoute = _paramsId.split('_')[0];
     // 因为短域名原因手动添加VUE_APP_Get_TenantId
    this.gameTenantId = process.env.VUE_APP_Get_TenantId;

    this.getDict();
    this.getDictByType(['district']);
    this.getGameInfoByGameRoute();
    this.stepactive();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    reGetUserType() {
      this.pageLoading = true;
      api_GET_EventsManagementUserUserType()
        .then(res => {
          this.$store.dispatch('user/getSaveCurrentUserType', res);
          this.pageLoading = false;
        });
    },
    stepactive() {
      // if(this.$route.query.delegationId === undefined) {
      //   return;
      // }
      const _vo = {
        competitionId: this.$route.query.id,
        delegationId: this.requiredIdData.delegationId
      };
      api_POST_EventsManagementEntryOrderAllowEntry(_vo).then(
          res => {
            if(res.insuranceOrderInfo) {
              if(!this.$route.query.insurance) {
                this.$router.push({
                query: {
                  insurance: true,
                  delegationId: this.requiredIdData.delegationId,
                }
              });
              }
              this.stepActive = 4;

            } else {
              this.stepActive = 0;
            }
          }
        )
        .catch(
          error => {
            this.$message({
              message: `费用获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 根据赛事路由获取赛事信息
    getGameInfoByGameRoute() {
      const gameQO = {
        IncludeStatus: true,
        IncludeType: true,
        IncludeApproveStatus: true,
        IncludeLevel: true,
        IncludeSetting: true,
        IncludeReportSetting: true,
        IncludeEntryFields: true
      };
      gameQO.route = this.gameRoute;
      if (this.gameTenantId) {
        gameQO.__tenant = this.gameTenantId;
      }
      api_GET_EventsManagementCompetitionWithRoute(gameQO).then(res => {
        this.gameInfo = res || {};
        this.gameId = this.gameInfo.id;
        this.checkGameCanEntry();
        console.log('getGameInfoByGameRoute -> this.gameInfo', this.gameInfo);
      });
    },
    // 检查赛事是否可以报名
    checkGameCanEntry () {
      // 如果赛事不在报名阶段，则跳转至赛事首页
      const _gameInfo = this.gameInfo;
      const _status = _gameInfo.status;
      const _gameRoute = this.$route.params.id;
      if (_status.code !== 'EntryStarted') {
        this.$message({
          message: `赛事不在报名时间内，无法报名！`,
          type: 'warning',
          showClose: true
        });
        this.$router.push({
          path: '/home/' + _gameRoute
        });
      } else {
        this.checkUserAndUserteamReady();
      }
    },
    // 获取用户信息
    getUserInfo() {
      // 获取个人注册信息
      if (this.UserType.registerId) {
        const _qo = {
          IncludeDelegation: true
        };
        api_GET_EventsManagementRegisterId(this.UserType.registerId, _qo)
          .then(res => {
            this.userInfo = res;
            console.log('getUserInfo -> userInfo', res);
            if (this.UserType.userType.code === 'Personal') {
              this.requiredIdData.delegationId = res.delegationId;
            }
          })
          .catch(
            error => {
              console.log('getUserInfo -> error: 获取用户信息失败', error);
              this.$message({ type: 'error', message: '获取用户信息失败' });
            }
          );
      } else {
        console.log('UserType中缺失registerId');
      }
    },
    // 获取团体注册信息
    getUserTeamInfo() {
      if (this.UserType.delegationId) {
        api_GET_EventsManagementDelegationId(this.UserType.delegationId)
          .then(res => {
            this.userTeamInfo = res;
            console.log('getUserTeamInfo -> userTeamInfo', res);
          })
          .catch(
            error => {
              console.log('getUserTeamInfo -> error: 获取团体信息失败', error);
              this.$message({ type: 'error', message: '获取团体信息失败' });
            }
          );
      } else {
        console.log('UserType中缺失delegationId');
      }
    },
    // 根据Step0类型选择修改当前类型
    changeCurrentUserType (data) {
      this.currentUserType = data.code;
    },
    changeRequiredIdData() {
      if (this.UserType.userType.code === 'PersonalDelegation' && this.currentUserType === 'Personal') {
        this.requiredIdData.delegationId = this.userInfo ? this.userInfo.delegationId : null;
      }
      if (this.UserType.userType.code === 'PersonalDelegation' && this.currentUserType === 'Delegation') {
        this.requiredIdData.delegationId = this.UserType.delegationId;
      }
    },
    // 从子模块获取官员数据
    changeOfficialData (data) {
      this.officialData = data;
      console.log(this.officialData);
    },
    // 添加附加的裁判教练或其他人员
    addAttachOfficial (data) {
      const _officicalData = this.attachOfficial.find(item => item.id === data.id);
      if (_officicalData) {
        const _tagData = _officicalData.registerTags.find(item => {
          return item.registerTagTypeCode === data.registerTags[0].registerTagTypeCode;
        });
        if (!_tagData) {
          _officicalData.registerTags.push(data.registerTags[0]);
        }
      } else {
        this.attachOfficial.push(data);
      }
    },
    // 用于修改报项，保证信息完整的情况下进行跳转
    checkUserAndUserteamReady() {
      const _gameInfoId = this.gameInfo ? this.gameInfo.id : '';
      const _gameSetting = this.gameInfo ? this.gameInfo.setting : '';
      const _modifyType = this.$route.query.modifyType;

      // 赛事id存在 且 赛事有配置 且 类型为修改
      if (this.UserType && _gameInfoId && _gameSetting && _modifyType) {
        // 修改类型为个人
        if (_modifyType === 'Personal') {
          this.$nextTick(() => {
            this.$refs['entry-step-by-type'][0].chooseConfirmInfo({
              name: '个人报名通道',
              code: 'Personal'
            }, 0);
          });
        }
        //  修改类型为团体
        if (_modifyType === 'Delegation') {
          this.$nextTick(() => {
            this.$refs['entry-step-by-type'][0].chooseConfirmInfo({
              name: '代表队报名通道',
              code: 'Delegation'
            }, 1);
          });
        }
      }
    },
    // 执行上一步
    doPrevStep () {
      if (this.stepActive <= 0) {
        return false;
      }
      this.stepActive--;
      return true;
    },
    // 执行下一步
    doNextStep () {
      if (this.stepActive >= this.stepMaxLen) {
        return false;
      }
      this.stepActive++;
      return true;
    }
  }
};
</script>

<style lang="scss" scoped>
.game_page {
  position: relative;
  min-height: 500px;
  padding: 10px 50px 130px;
}

.step_title {
  position: relative;
  height: 32px;
  margin-bottom: 20px;
  line-height: 32px;
  font-size: 18px;
  font-weight: bold;
  color: #353434;
}
.step_title::after {
  display: block;
  content: "";
  position: absolute;
  left: -18px;
  top: 0;
  width: 6px;
  height: 32px;
  border-radius: 4px;
  background-color: #E02020;
}
.step_mb {
  margin-bottom: 20px;
}
.gl_dataError {
  padding: 100px 0 60px;
  text-align: center;
  color: #606266;
}
</style>

<style>
.home_game_entry .confirmInfo_title {
  position: relative;
  height: 32px;
  margin-bottom: 16px;
  line-height: 32px;
  font-size: 18px;
  font-weight: bold;
  color: #353434;
}
.home_game_entry .confirmInfo_title::after {
  display: block;
  content: "";
  position: absolute;
  left: -18px;
  top: 0;
  width: 6px;
  height: 32px;
  border-radius: 4px;
  background-color: #E02020;
}

.home_game_entry .gameEntry_shadow {
  border-radius: 8px;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
}

.home_game_entry .control_row {
  padding-top: 30px;
}
</style>
